﻿using Container.Library;
using Hangfire;
using DevOps.Logic;
using System;
using static Scheduler.Library.Scheduler;
using static Scheduler.Library.Trigger;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
using System.Threading;
using Common.Library;

/*
* 命名空间: Api.DevOpsManage.App_Start
*
* 功 能： 接口服务端定时任务管理
*
* 类 名： SchedulerManage
*
* Version   变更日期            负责人     变更内容
* ─────────────────────────────────────────────────
* V1.0.1    2020/4/13 10:10:04 				罗维     创建
*
* Copyright (c) 2020 Lir Corporation. All rights reserved.
*/

namespace Api.DevOpsManage.App_Start
{

    /// <summary>
    /// 接口服务端定时任务管理
    /// </summary>
    public class SchedulerManage : IHostedService, IDisposable
    {
        /// <summary>
        /// 接口访问监控日志Redis操作类实例
        /// </summary>
        private IApiMonitorLogService apiMonitorLogService = null;

        /// <summary>
        /// 构造函数
        /// </summary>
        public SchedulerManage()
        {
            apiMonitorLogService = UnityCIContainer.Instance.GetService<IApiMonitorLogService>();
        }

        /// <summary>
        /// 启动任务绑定
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            NLogHelper.LogInfo("定时任务被启动", "...start...");

            HanfireStart();

            TriggerStart();

            return Task.CompletedTask;
        }

        /// <summary>
        /// 任务关闭时执行
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            NLogHelper.LogInfo("定时任务被关闭", "...end...");
            return Task.CompletedTask;
        }
        /// <summary>
        /// 释放托管资源，释放时触发
        /// </summary>
        public void Dispose()
        {
            NLogHelper.LogInfo("定时任务被释放闭", "...Dispose...");
        }

        #region 任务逻辑

        /// <summary>
        /// 开启Hanfire定时任务
        /// </summary>
        public void HanfireStart()
        {
            //清空Hangfire信息
            ApiMonitorLogServiceRedis.EmptyHangfire();

            //删除过期接口访问记录信息
            RemoveExpiredApiLog();

            //删除过期接口访问记录统计信息
            RemoveExpiredGroupInfo();
        }

        /// <summary>
        /// 开启Trigger定时任务
        /// </summary>
        public void TriggerStart()
        {
            //统计接口请求信息
            StatisticsInterfaceRequest();
        }

        #region Hangfire

        /// <summary>
        /// 删除过期接口访问记录信息【失效时间10分钟，有配置】
        /// </summary>
        private void RemoveExpiredApiLog()
        {
            string JobId = "RemoveExpiredApiMonitorLog";

            RecurringJob.AddOrUpdate(JobId, () => ApiMonitorLogServiceRedis.RemoveExpiredApiMonitorLog(), Cron.Minutely());
        }

        /// <summary>
        /// 删除过期接口访问记录统计信息【失效时间10分钟，有配置】
        /// </summary>
        private void RemoveExpiredGroupInfo()
        {
            string JobId = "RemoveExpiredGroupInfo";

            RecurringJob.AddOrUpdate(JobId, () => ApiMonitorLogServiceRedis.RemoveExpiredGroupInfo(), Cron.Minutely());
        }
        #endregion

        #region Trigger

        /// <summary>
        /// 统计接口请求信息
        /// 【
        /// Harvey.Framework:ApiMonitorStatistics，
        /// Harvey.Framework:ApiMonitorPathStatistics，
        /// Harvey.Framework:ApiMonitorPathIpStatistics，
        /// Harvey.Framework:ApiMonitorNameList 
        /// 】
        /// </summary>
        private void StatisticsInterfaceRequest()
        {
            //间隔统计时间
            int seconds = 5;

            ScheduleTask("StatisticsInterfaceRequest", NewTrigger.Every(new TimeSpan(0, 0, seconds)).StartAt(DateTime.Now), () =>
            {
                apiMonitorLogService.StatisticsInterfaceRequest(seconds);
            });
        }
        #endregion

        #endregion
    }
}
